package com.android.fragmentdemo.util
import android.content.Context
import android.content.SharedPreferences
import java.io.IOException

class SharedPreferencesUtil private constructor() {
    companion object {
        private const val KEY = "data_store"

        private var sharedPreferences: SharedPreferences? = null

        fun init(context: Context) {
            sharedPreferences = context.getSharedPreferences(KEY, Context.MODE_PRIVATE)
        }

        fun putString(key: String, value: String?) {
            sharedPreferences?.edit()?.putString(key, value)?.apply()
            try {
                /*针对断电数据保存丢失问题*/
                Runtime.getRuntime().exec("sync")
            } catch (ex: IOException) {
                ex.printStackTrace()
            }
        }

        fun getString(key: String): String? {
            return sharedPreferences?.getString(key, "")
        }

        fun putInt(key: String, value: Int) {
            sharedPreferences?.edit()?.putInt(key, value)?.apply()
            try {
                /*针对断电数据保存丢失问题*/
                Runtime.getRuntime().exec("sync")
            } catch (ex: IOException) {
                ex.printStackTrace()
            }
        }

        fun getInt(key: String, defaultValue: Int = 0): Int {
            return sharedPreferences?.getInt(key, defaultValue) ?: defaultValue
        }
    }
}